<?php

/**
 * ChangePasswordForm class
 * 
 * ChangePasswordForm is the data structure for keeping
 * change password form data. It is used by the 'changePassword' action of 'User'.
 * @property string $oldPassword
 * @property string $newPassword
 * @property string $comfirmedPassword
 */
class ChangePasswordForm extends CFormModel
{
	public $oldPassword;
	public $newPassword;
	public $comfirmedPassword;

	// an object of class UserIdentify.
	//private $_identity;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and oldPassword needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			// username and password are required
			array('oldPassword, newPassword, comfirmedPassword', 'required'),
			// newPassword and comfirmedPassword should be same
			array('newPassword', 'compare', 'compareAttribute'=>'comfirmedPassword'),
			// newPassword and oldPassword should not be same
			array('newPassword', 'compare', 'compareAttribute'=>'oldPassword','operator'=>'!=', 'message'=>'The new password should not be same as the old password'),
			// oldPassword needs to be authenticated
			array('oldPassword', 'authenticate'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			// label of username and password will be automatically generated according to the attribute name.
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		// If there is any other validation error, this validation will not be carried out.
		if(!$this->hasErrors())
		{
			$identity=new UserIdentity(Yii::app()->user->name,$this->oldPassword);
			if(!$identity->authenticate())
				// Add validation errors to the error array.
				$this->addError('oldPassword','Old password is incorrect.');
		}
	}
}
